import { useAppDispatch } from "@/hooks/storeHooks";
import { promptResult } from "@/utils/common";
import { checkLogin } from "@/utils/redux/slices/authSlice";
import { useEffect, useState, type ComponentType } from "react";
import { Loading, Overlay } from "react-vant";

const withAuth = (WrappedComponent: ComponentType) => {
  function AuthedComponent(props: any) {
    const [isLogined, setIsLogined] = useState(false);
    const dispatch = useAppDispatch();

    useEffect(() => {
      const func = async () => {
        promptResult(
          dispatch(checkLogin()),
          () => {},
          () => {
            setIsLogined(true);
          }
        );
      };
      func();
    }, []);
    if (isLogined) {
      return <WrappedComponent {...props} />;
    } else {
      return (
        <Overlay visible={true}>
          <div
            style={{
              width: "100%",
              height: "100%",
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
            }}
          >
            <Loading type="ball" />
          </div>
        </Overlay>
      );
    }
  }
  return AuthedComponent;
};

export default withAuth;
